//
// Created by antler on 2018/12/5.
//

#include "lprefix.h"

#include <string>

#include "lua.hpp"
#include "luaext.hpp"

#include "RuntimeUtils.h"

static int runtime_launchApp(lua_State *L) {
    int argc = lua_gettop(L);
    if (argc < 1) {
        lua_pushliteral(L, "need more params");
        lua_error(L);
    }

    const char *packageName = luaL_checkstring(L, 1);
    const char *componentName = luaL_optstring(L, 2, nullptr);

    bool result = RuntimeUtils::launchApp(packageName, componentName);
    lua_pushboolean(L, result ? 1 : 0);
    return 1;
}

static int runtime_killApp(lua_State *L) {
    int argc = lua_gettop(L);
    if (argc < 1) {
        lua_pushliteral(L, "need more params");
        lua_error(L);
    }

    const char *packageName = luaL_checkstring(L, 1);

    RuntimeUtils::killApp(packageName);
    return 0;
}

static int runtime_inputText(lua_State *L) {
    int argc = lua_gettop(L);
    if (argc < 1) {
        lua_pushliteral(L, "need more params");
        lua_error(L);
    }

    const char *inputText = luaL_checkstring(L, 1);

    RuntimeUtils::inputText(inputText);
    return 0;
}

static const luaL_Reg funcs[] = {
        {"launchApp", runtime_launchApp},
        {"killApp",   runtime_killApp},
        {"inputText", runtime_inputText},
        {NULL, NULL}
};

LUAMOD_API int luaopen_runtime(lua_State *L) {
    luaL_register(L, "runtime", funcs);
    return 0;
}